/** 
 * Copyright: Copyright (c)2011
 * Company: 易宝支付(YeePay) 
 */
package net.loyintean.pearlshell.validation.rule;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import net.loyintean.pearlshell.validation.IValidRule;
import net.loyintean.pearlshell.validation.IValidRuleConfig;

/** string符合给定的正则表达式的校验实现类
 * <p>
 * 
 * @author：jun.lin@yeepay.com
 * @since：2014年12月5日 下午3:12:36
 * @version: */
class StringMatchRegexValidRuleImpl extends AbstractStringValidRuleImpl
		implements IValidRule, INeedAdditionConfig {

	StringMatchRegexValidRuleImpl() {
		super();
	}

	/** @see net.loyintean.pearlshell.validation.
	 *      IValidRule#errorMsg(IValidRuleConfig) */
	@Override
	public String errorMsg(IValidRuleConfig config) {
		String msg;
		try {
			msg = (String) config.validParam()[1];

		} catch (ArrayIndexOutOfBoundsException e) {
			msg = "不能匹配给定的正则表达式";
		}

		return msg;
	}

	/** @see net.loyintean.pearlshell.validation.rule.
	 *      AbstractStringValidRuleImpl#validString(String, IValidRuleConfig) */
	@Override
	protected boolean validString(String toValid, IValidRuleConfig config) {

		Pattern p = Pattern.compile((String) config.validParam()[0]);

		Matcher matcher = p.matcher(toValid);

		// jun.lin 2015-03-20 这里应该是mathces，不是find
		return matcher.matches();
	}

	/** 检查附加配置参数是否有效。
	 * <p>
	 * 要求：
	 * <ul>
	 * <li>第一个参数：必填；<br>
	 * 是string类型，并且可以被java正则识别；将用作正则校验的表达式。</li>
	 * <li>第二个参数：选填；是string类型；将用作校验失败时的错误提示。</li>
	 * </ul>
	 * 
	 * @see net.loyintean.pearlshell.validation.rule.
	 *      INeedAdditionConfig#isValidParamIllegal(IValidRuleConfig) */
	@Override
	public void isValidParamIllegal(IValidRuleConfig config)
			throws IllegalArgumentException {

		try {
			if (config.validParam()[0] instanceof String) {
				Pattern.compile((String) config.validParam()[0]);
			} else {
				// 用空指针异常来指示错误
				throw new NullPointerException();
			}
		} catch (NullPointerException e) {
			// 用这个空指针异常来捕捉：
			// config == null || config.validParam() == null
			// || config.validParam().length == null
			// 以及try里面处理过的!(config.validParam()[0] instanceof Integer)
			throw new IllegalArgumentException("没有指定正则表达式！", e);
		} catch (PatternSyntaxException e) {
			throw new IllegalArgumentException("指定了错误的正则表达式！", e);
		}

		try {
			if (!(config.validParam()[1] instanceof String)) {
				throw new IllegalArgumentException(
						"正则表达式校验错误提示信息配置错误！必须是string类型！");
			}
		} catch (NullPointerException e) {
			// 可以不设置第二个参数
		}
		// 其它异常概不处理。
	}

}
